<template>
  <!-- 搜索表单 -->
  <el-form inline="true" class="board-form" style="margin-bottom: 20px">
    <el-form-item style="margin-right: 20px">
      <el-input v-model="params.boardName" placeholder="请输入标签名称" style="width: 240px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSearch">搜索</el-button>
      <el-button @click="onReset">重置</el-button>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">新增标签</el-button>
    </el-form-item>
    <el-form-item>
      <el-radio-group v-model="params.sortOrder" @change="getBoardList">
        <el-radio-button label="asc">正序</el-radio-button>
        <el-radio-button label="desc">倒序</el-radio-button>
      </el-radio-group>
    </el-form-item>
  </el-form>

  <!-- 标签表格 -->
  <el-table
    :data="boardList"
    row-key="boardId"
    v-loading="loading"
    style="width: 100%"
  >
    <el-table-column label="排序" width="120">
      <template #header>
        <span>排序</span>
        <el-tooltip content="拖拽可调整顺序" placement="top">
          <el-icon class="sort-tip"><InfoFilled /></el-icon>
        </el-tooltip>
      </template>
      <template #default="{ $index }">
        <el-icon class="drag-handle" :size="16">
          <Rank />
        </el-icon>
        <span style="margin-left: 8px">{{ params.sortOrder === 'asc' ? $index + 1 : boardList.length - $index }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="boardName" label="标签名称" width="180" />
    <!-- 将标签描述列移到标签名称列后面 -->
    <el-table-column label="标签描述" width="200">
      <template #default="{ row }">
        <el-tooltip content="点击查看完整描述" placement="top">
          <span @click="showFullDescription(row.description)" class="description-text">
            {{ (row.description || '').length > 20 ? (row.description || '').slice(0, 20) + '...' : row.description || '' }}
          </span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="postCount" label="帖子数量" width="100" />
    <el-table-column prop="state" label="状态" width="100">
      <template #default="{ row }">
        <el-tag :type="row.state === 0 ? 'success' : 'danger'">
          {{ row.state === 0 ? '正常' : '禁用' }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="nickName" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180">
      <template #default="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180" fixed="right">
      <template #default="{ row }">
        <el-button type="text" @click="showEditDialog(row)">编辑</el-button>
        <el-button type="text" class="red" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    v-model:current-page="params.pageNum"
    v-model:page-size="params.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px;"
  />

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="标签名称" prop="boardName">
        <el-input v-model="form.boardName" placeholder="请输入标签名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort" v-if="isEdit">
        <el-input-number v-model="form.sort" :min="1" :max="100" :disabled="!isEdit" />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-radio-group v-model="form.state">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标签描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入标签描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 完整描述弹窗 -->
  <el-dialog v-model="showFullDescDialog" title="完整描述" width="500px">
    <p>{{ fullDescription }}</p>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { Plus, Rank, InfoFilled } from '@element-plus/icons-vue'
import { 
  getBoardListService, 
  addBoardService, 
  updateBoardService, 
  deleteBoardService,
  batchUpdateSortService
} from '@/apis/board'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'

const sortable = ref(null);

// 搜索参数
const params = reactive({
  pageNum: 1,
  pageSize: 10,
  boardName: '',
  sortOrder: 'asc' // 新增排序方式参数
})

// 表格数据
const boardList = ref([])
const total = ref(0)
const loading = ref(false)

// 弹窗相关c
const dialogVisible = ref(false)
const form = reactive({
  boardId: null,
  boardName: '',
  description: '',
  sort: 1,
  state: 0
})
const formRef = ref(null)
const isEdit = ref(false)

// 弹窗标题
const dialogTitle = computed(() => isEdit.value ? '编辑标签' : '新增标签')

// 表单验证规则
const rules = reactive({
  boardName: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ]
})

// 初始化拖拽排序
const initSortable = () => {
  const el = document.querySelector('.el-table__body-wrapper tbody');
  if (el) {
    sortable.value = new Sortable(el, {
      animation: 150,
      handle: '.drag-handle',
      ghostClass: 'sortable-ghost',
      onEnd: async ({ newIndex, oldIndex }) => {
        if (newIndex === oldIndex) return;
        
        const currRow = boardList.value.splice(oldIndex, 1)[0];
        boardList.value.splice(newIndex, 0, currRow);
        await updateSortOrder();
      }
    });
  }
};

// 更新排序显示
const updateSortDisplay = () => {
  boardList.value.forEach((item, index) => {
    item.displaySort = params.sortOrder === 'asc' ? index + 1 : boardList.value.length - index
  })
}

// 更新排序到后端
const updateSortOrder = async () => {
  const sortData = boardList.value.map((item, index) => ({
    boardId: item.boardId, // 确保转为数字类型
    sort: index + 1 // 实际排序值始终为正序
  }));
  
  try {
    await batchUpdateSortService(sortData);
    ElMessage.success('排序更新成功');
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '排序更新失败');
    getBoardList(); // 失败后重新加载
  }
};

// 获取标签列表
const getBoardList = async () => {
  try {
    loading.value = true;
    const res = await getBoardListService(params);
    console.log('获取的标签列表数据:', res.rows); // 打印返回的数据
    boardList.value = res.rows.map(item => ({
      ...item,
      displaySort: params.sortOrder === 'asc' 
        ? item.sort 
        : res.total - item.sort + 1
    }));
    total.value = res.total;
    
    // 确保数据加载完成后初始化拖拽
    nextTick(() => {
      if (sortable.value) {
        sortable.value.destroy();
      }
      initSortable();
    });
  } catch (error) {
    console.error('获取标签列表失败:', error);
    ElMessage.error('获取标签列表失败');
  } finally {
    loading.value = false;
  }
};

// 初始化加载数据
onMounted(getBoardList)

// 分页处理
const handleSizeChange = (newSize) => {
  params.pageSize = newSize
  params.pageNum = 1
  getBoardList()
}

const handleCurrentChange = (newPage) => {
  params.pageNum = newPage
  getBoardList()
}

// 搜索和重置
const onSearch = () => {
  params.pageNum = 1
  getBoardList()
}

const onReset = () => {
  params.pageNum = 1
  params.pageSize = 10
  params.boardName = ''
  getBoardList()
}

// 显示新增弹窗
const showAddDialog = () => {
  isEdit.value = false
  form.boardId = null
  form.boardName = ''
  form.sort = undefined // 不设置排序值，由后端自动处理
  form.state = 0
  form.description = '' // 重置描述
  dialogVisible.value = true
}

// 显示编辑弹窗
const showEditDialog = (row) => {
  isEdit.value = true;
  form.boardId = row.boardId;
  form.boardName = row.boardName;
  form.sort = row.sort;  // 确保获取当前排序值
  form.state = row.state;
  form.description = row.description // 填充描述
  dialogVisible.value = true;
};

// 提交表单时处理可能的错误
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    
    if (isEdit.value) {
      await updateBoardService({
        boardId: form.boardId,
        boardName: form.boardName,
        sort: form.sort, // 可以为null，后端会处理
        state: form.state,
        description: form.description // 新增描述字段
      });
      ElMessage.success('更新成功');
    } else {
      await addBoardService({
        ...form,
        description: form.description // 新增描述字段
      });
      ElMessage.success('新增成功');
    }
    
    dialogVisible.value = false;
    getBoardList();
  } catch (error) {
    // 显示具体的错误信息
    ElMessage.error(error.response?.data?.msg || error.message || '操作失败');
  }
};

// 删除标签
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该标签吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBoardService(row.boardId)
      ElMessage.success('删除成功')
      getBoardList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 新增完整描述弹窗相关变量
const showFullDescDialog = ref(false)
const fullDescription = ref('')

// 显示完整描述
const showFullDescription = (description) => {
  // Add a null check
  fullDescription.value = description || ''; 
  showFullDescDialog.value = true;
};
</script>

<style scoped>
.board-form {
  margin-bottom: 20px;
}

.drag-handle {
  cursor: move;
  color: #999;
}

.red {
  color: #F56C6C;
}

.sort-tip {
  margin-left: 5px;
  color: #999;
  cursor: help;
}

/* 拖拽时的幽灵元素样式 */
:deep(.sortable-ghost) {
  opacity: 0.5;
  background: #c8ebfb;
}
.description-text {
  cursor: pointer;
  color: #409EFF;
  text-decoration: underline;
}
</style>